<template>
  <van-form  @submit="onSubmit">

    <!-- 单选（如性别） -->
    <van-radio-group v-if="editUser.editKey === 'gender'" v-model="editUser.currentValue">
      <van-radio :name="0"  class="gender-radio" >男</van-radio>
      <van-radio :name="1"  class="gender-radio" >女</van-radio>
    </van-radio-group>

<!--     文件上传 -->
    <div v-else-if="editUser.editKey === 'avatarUrl'" style="display: flex; align-items: center; justify-content: center; gap: 40px;">
      <!--旧图像-->
      <img style="height: 80px" :src="editUser.currentValue"/>

      <van-icon name="arrow" />
<!--      <van-icon name="arrow-double-left" />-->

      <!--新头像-->
      <van-uploader
          v-model="fileList"
          :after-read="afterRead"
          :max-count="1"
          accept="image/*"
          result-type="file"
      >
      </van-uploader>
    </div>



    <van-field v-else
        v-model ="editUser.currentValue"
        :name="editUser.editKey"
        :label="editUser.editName"
        :placeholder="`请输入${editUser.editName}`"
    />
    <div style="margin: 16px;">
      <van-button round block type="primary" native-type="submit">
        提交
      </van-button>
    </div>
  </van-form>

</template>

<script setup lang="ts">
import {useRoute, useRouter} from "vue-router";
import myAxios from '../plugins/myAxios'
import {ref,onMounted} from "vue";

import {getCurrentUser} from "../service/user.ts";
import {Toast} from "vant";
// const router = useRouter();
const route = useRoute();
const router = useRouter();
const editUser = ref({
  editKey:route.query.editKey ,
  editName:route.query.editName,
  currentValue:route.query.displayValue
})
console.log(editUser)
// 保存初始值
const originalValue = ref<any>('')

onMounted(() => {
  originalValue.value = editUser.value.currentValue
})

const onSubmit = async () => {
  const currentUser = await getCurrentUser();

  if (!currentUser) {
    // await showToast({
    //   overlay:false,
    //   type:'fail',
    //   message:"暂时未登录！"
    // })
    await router.push({
      path: '/setting',
    })
    return;
  }
  if (fileObj) {
    const formData = new FormData();
    formData.append('avatar', fileObj); // 将文件添加到 FormData 中
    console.log(formData)
    const res = await myAxios.post('/file/avatar/upload', formData,{
      headers: {
        "Content-Type": "multipart/form-data"
      }
    })
    if (res.code === 0 && res.data) {
      router.back();
    } else {
      Toast.fail('修改错误');
    }
    return;
  }
  const res = await myAxios.post('/user/updateInfo', {
    'id': currentUser.id,
    // [editUser.value.editKey as string]: editUser.value.currentValue
    [editUser.value.editKey as string]:
        (editUser.value.currentValue === '' || editUser.value.currentValue === undefined)
            ? originalValue.value // 没选择，用原值
            : editUser.value.currentValue // 选择了，用新值
  })
  console.log(res, '更新请求', editUser.value.currentValue);
  if (res.code === 0 && res.data) {
    router.back();
  } else {
    Toast.fail('修改错误');
  }
};

const fileList = ref([])
let fileObj = fileList[0]; // 上传的头像文件列表

// 上传后处理逻辑
const afterRead = (file) => {
  // file.file 是原始文件对象，可以上传到后端
  fileObj = file.file;

  // 这里可以调用你的 API 上传文件到服务器 / COS
  // 例如：uploadAvatar(file.file).then(res => ...)
};

</script>

<style scoped>
.gender-radio{
  margin: 16px;
}
</style>